const del = require('del')
const gulp = require("gulp");
const gutil = require("gulp-util");

// 环境变量
const env = {
  MODE: 'all'
}

// 获取用户配置
const config = require("./gulp.config.js");

// 日志输出
function log() {
  const args = Array.prototype.slice.call(arguments);
  gutil.log.apply(null, args);
}

// 复制文件
function copyFile(files, output, entry) {
  if (files && files.length) {
    return gulp
      .src(files, { allowEmpty: true, base: entry || config.entry })
      .pipe(gulp.dest(output));
  } else {
    return log("请配置gulp.config.js内容~");
  }
}

async function copy() {
  const { MODE } = env
  log(MODE)
  const conf = config

  log(`将${conf.entry}目录中通用文件同步到[${conf.output}]目录中...`);
  return conf.output.forEach(item => {
    const filters = []
    conf.filters.forEach(row => {
      if (typeof row === 'object') {
        // 过滤指定项目
        if (row.output.includes(item)) {
          filters.push(`!${conf.entry}${row.value}`)
        }
      } else {
        // 全部过滤
        filters.push(`!${conf.entry}${row}`)
      }
    })
    const files = [...conf.files.map(item => conf.entry + item), ...filters]
    // console.log(files)
    return copyFile(files, item, conf.entry);
  })
}

// clean
function clean() {
  return del(['./uni-hq/dist', './uni-hq/src/unpackage', './uni-hzl/src/unpackage', './uni-hzl/dist'])
}

// clean
exports['clean'] = gulp.series(clean)

// 同步文件
gulp.task("copy", gulp.series(copy));
